package me.huanmeng.heater.runnable;

import cn.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.SneakyThrows;
import me.huanmeng.heater.Heater;
import me.huanmeng.heater.api.event.SignallingEvent;
import me.huanmeng.heater.bot.MessageHelper;
import me.huanmeng.heater.main.HeaterMain;
import me.huanmeng.heater.signalling.Signalling;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 2021/10/2<br>
 * Heater<br>
 *
 * @author huanmeng_qwq
 */
public class SignallingHandleRunnable extends Thread implements MessageHelper {
    private final List<Handler<Signalling>> pending = new ArrayList<>();
    public SignallingHandleRunnable() {
        super("Sign Handle");
    }

    @SneakyThrows
    @Override
    public void run() {
        while (HeaterMain.getInstance().isRunning()) {
            final List<Handler<Signalling>> handlers = get(RandomUtil.randomInt(10, 20));
            if(!handlers.isEmpty()){
                for (Handler<Signalling> handler : handlers) {
                    final Signalling data = handler.getData();
                    execute(data);
                }
                pending.removeAll(handlers);
            }
            sleep(10);
        }
    }
    final void execute(Signalling signalling){
        signalling.execute();
        Heater.callEvent(new SignallingEvent(signalling));
    }

    final List<Handler<Signalling>> get(int count) {
        if(pending.isEmpty()){
            return Collections.emptyList();
        }
        return pending.stream().sorted(Comparator.comparingInt(Handler::getIndex)).limit(count).collect(Collectors.toList());
    }

    public void add(Signalling signalling) {
        pending.add(new Handler<>(signalling.getSn(), signalling));
    }

    @AllArgsConstructor
    @Getter
    private static class Handler<T> {
        private final int index;
        private final T data;
    }
}
